#ifndef __EMB_MEMBLK_H
#define __EMB_MEMBLK_H


#include "emb_memblk.h"

typedef struct{
    void *FreeList;
} emb_memblk_ctrl_t;

int emb_memblk_init(emb_memblk_ctrl_t *Blk, uint8_t *Buf, size_t BufSize,size_t BlkSize)
{
    size_t i;
    size_t blk_count = BufSize / BlkSize;

    Blk->FreeList = Buf;
    for (i = 0; i < blk_count-1; i++)
    {
        *(void**)(Buf+(i*BlkSize))=(Buf+(i*(BlkSize+1)));
    }

    *(void**)(Buf + (i * BlkSize)) = NULL;
}

static inline void* emb_memblk_alloc(emb_memblk_ctrl_t* Blk)
{
    void *ptr;
    if (Blk->FreeList == NULL)
    {
        return NULL;
    }

    ptr = Blk->FreeList;
    Blk->FreeList = *(void**)(Blk->FreeList);

    return ptr;
}

static inline void emb_memblk_free(emb_memblk_ctrl_t*Blk,void* Ptr)
{
    EMB_PORT_DISABLE_IRQ();
    *(void **)Ptr = Blk->FreeList;
    Blk->FreeList = Ptr;
    EMB_PORT_ENABLE_IRQ();
}

#endif